import 'dart:async';
import 'package:flutter/material.dart';
import 'package:hx_im_plugin/hx_im_plugin.dart';
import 'package:hx_im_plugin_example/hq_im_ui/widgets/hq_common_widgets.dart';

class HqGroupMembersMenu extends StatefulWidget {

  final EMConversation conv;
  HqGroupMembersMenu(EMConversation conversation) : conv = conversation;

  @override
  _HqGroupMembersMenuState createState() => _HqGroupMembersMenuState();
}

class _HqGroupMembersMenuState extends State<HqGroupMembersMenu> {

  /// 展示显示全部成员按钮
  bool isShowButton = false;

  /// 展示全部成员
  bool isShowAllMembers = false;

  /// 中间数组
  List members = [];

  /// 群成员List
  List _memberList = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _getGroupUsers();
  }

  _initData() {
    setState(() {
      members = [];
      if(_memberList.length < 6) {
        isShowButton = false;
        members = _memberList;
        return;
      }
      for(int i = 0; i < 4; i++) {
        members.add(_memberList[i]);
      }
      isShowButton = true;
    });
  }

  /// 获取群成员列表
  _getGroupUsers() async {
    try {
      EMCursorResult result = await EMClient.getInstance.groupManager.getGroupMemberListFromServer(widget.conv.id);
      print(result.data.toString());
      result.data.forEach((element) {
        _memberList.add({"name": element, "image": "images/contact_default_avatar.png", "msg": "0"});
      });
      _initData();
    } on EMError catch(e) {
      print('操作失败，原因是: $e');
    }
  }


  @override
  Widget build(BuildContext context) {

    Size size = MediaQuery.of(context).size;

    return Container(
      constraints: BoxConstraints(
          minHeight: sHeight(60),
          maxHeight: sHeight(isShowAllMembers ? 290 : 60)
      ),
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [
          BoxShadow(
            color: Color.fromRGBO(0, 0, 0, 1),  /// 底色,阴影颜色
            offset: Offset(0, 100), /// 阴影位置,从什么位置开始
            blurRadius: 1,  /// 阴影模糊层度
            spreadRadius: 0,  /// 阴影模糊大小
          ),
        ],
      ),
      child: Stack(
        children: [
          GridView.builder(
            // physics: NeverScrollableScrollPhysics(), /// 增加禁止滚动<解决listview和gridview嵌套使用>
            // shrinkWrap: true, /// 增加禁止滚动<解决listview和gridview嵌套使用>
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
              /// 设置列数
              crossAxisCount: 5,
              /// 设置横向间距
              crossAxisSpacing: sWidth(8),
              /// 设置主轴间距
              mainAxisSpacing: sHeight(13),
            ),
            scrollDirection: Axis.vertical,
            itemCount: members.length,
            itemBuilder:(context, index) {
              return HqGroupMemberInfo(infoMap: members[index],);
            },
          ),
          Positioned(
            right: sWidth(8),
            bottom: sHeight(6),
            child: isShowButton ?
            Container(
              height: sHeight(45),
              color: Colors.white,
              child: GestureDetector(
                onTap: () {
                  isShowAllMembers = !isShowAllMembers;
                  Timer(Duration(milliseconds: 60), () {
                    members = [];
                    if(isShowAllMembers) {
                      members = _memberList;
                    } else {
                      for(int i = 0; i < 4; i++) {
                        members.add(_memberList[i]);
                      }
                    }
                    if(!mounted)return;
                    setState(() {});
                  });
                },
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    Text('共120人', style: TextStyle(
                        fontSize: sFontSize(14),
                        color: Color.fromRGBO(96, 105, 114, 1),
                    ),),
                    Image.asset(
                      isShowAllMembers ? 'images/hq_group_members_menu_hide.png' : 'images/hq_group_members_menu_show.png',
                      width: sWidth(24),
                      height: sHeight(24),
                      fit: BoxFit.cover,
                    )
                  ],
                ),
              ),
            ) : Container(),
          )
        ],
      ),
    );
  }
}

/// group member 信息
class HqGroupMemberInfo extends StatelessWidget {

  final Map infoMap;
  HqGroupMemberInfo({this.infoMap});

  _getMsgNumber() {
    int msg = int.parse(infoMap["msg"]);
    if(msg <= 0) {
      return '';
    }

    if(msg < 10) {
      return msg.toString();
    }
    return "10+";
  }

  @override
  Widget build(BuildContext context) {

    return Container(
      child: Stack(
        children: [
          Container(
            alignment: Alignment.center,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                FlatButton(
                  padding: EdgeInsets.zero,
                  onPressed: () {
                  },
                  child: Container(
                    width: sHeight(27.5),
                    height: sHeight(27.5),
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(3),
                      border: Border.all(width: 0.5, color: Color.fromRGBO(221, 221, 221, 1.0)),
                    ),
                    child: Image.asset(
                      infoMap["image"],
                      width: sHeight(27.5),
                      height: sHeight(27.5),
                      fit: BoxFit.contain,
                    ),
                  ),
                ),
                SizedBox(height: sHeight(2),),
                Text(infoMap["name"], style: TextStyle(
                    fontSize: sFontSize(14),
                    color: Color.fromRGBO(29, 32, 35, 1.0),
                    fontWeight: FontWeight.bold
                ),),
              ],
            ),
          ),
          Positioned(
              right: sWidth(0),
              top: sHeight(2),
              child: _getMsgNumber() == '' ? Container() :
              Container(
                padding: EdgeInsets.fromLTRB(sWidth(3), sHeight(1), sWidth(3), sHeight(1)),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: Color.fromRGBO(255, 93, 93, 1.0),
                  borderRadius: BorderRadius.circular(4.5),
                  border: Border.all(width: 0.5, color: Colors.white),
                ),
                child: Text(_getMsgNumber(), style: TextStyle(
                    fontSize: sFontSize(10),
                    color: Colors.white,
                    fontWeight: FontWeight.bold
                ),),
              )
          )
        ],
      ),
    );
  }
}


